package com.atguigu.gmall.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.payment.mapper.OrderInfoMapper;
import com.atguigu.gmall.payment.mapper.PaymentInfoMapper;
import com.atguigu.gmall.payment.service.PaymentService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Service
public class PaymentServiceImpl implements PaymentService {
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private PaymentInfoMapper paymentInfoMapper;
    //在生成统一下单接口时,要先生成支付表
    @Override
    public PaymentInfo insert(Long orderId, PaymentType paymentType) {
        //1.在添加支付表时,要先查询是否已经生成了支付表,如果生成了支付表则修改支付方式,如果没有生成则添加
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(new QueryWrapper<PaymentInfo>()
                .eq("order_id", orderId));
        if (null != paymentInfo){
            //修改支付方式
            paymentInfo.setPaymentType(paymentType.name());
            paymentInfoMapper.updateById(paymentInfo);
        }else {
            //添加支付表
            paymentInfo = new PaymentInfo();
            //根据orderId查询order_info表
            OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
            paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
            paymentInfo.setOrderId(orderId);
            paymentInfo.setPaymentType(paymentType.name());
            paymentInfo.setTotalAmount(orderInfo.getTotalAmount());
            paymentInfo.setSubject(orderInfo.getTradeBody());
            paymentInfo.setPaymentStatus(PaymentStatus.UNPAID.name());
            paymentInfo.setCreateTime(new Date());
            paymentInfoMapper.insert(paymentInfo);
        }
        return paymentInfo;
    }

    //查询订单表
    @Override
    public PaymentInfo selectPayment(String out_trade_no) {
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(new QueryWrapper<PaymentInfo>().eq("out_trade_no", out_trade_no));
        return paymentInfo;
    }

    //订单完成后 对支付表进行更新
    @Override
    public void updatePaymentInfo(Map<String, String> paramsMap) {
        //1:注意幂等性问题 查询支付表
        PaymentInfo paymentInfo = selectPayment(paramsMap.get("out_trade_no"));
        //如果paymentInfo不为空 并且支付状态未支付中
        if (null != paymentInfo && PaymentStatus.UNPAID.name().equals(paymentInfo.getPaymentStatus())){
            //2:更新支付表
            paymentInfo.setPaymentStatus(PaymentStatus.PAID.name());
            //2.1 更新银行流水
            paymentInfo.setTradeNo(paramsMap.get("trade_no"));
            //2.2 更新回调时间
            try {
                paymentInfo.setCallbackTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                .parse(paramsMap.get("notify_time")));

                //2.3 更新回调内容
                String callbackContent = JSONObject.toJSONString(paramsMap);
                paymentInfo.setCallbackContent(callbackContent);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            paymentInfoMapper.updateById(paymentInfo);
            //3:发消息MQ 让MQ通知订单 更新订单状态 将orderId传过去 Long
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_PAYMENT_PAY, MqConst.ROUTING_PAYMENT_PAY,
                    paymentInfo.getOrderId());
        }
    }

     @Autowired
    private RabbitService rabbitService;
}
